import modal from '@/plugins/modal'
import store from '@/store'
import { getToken } from '@/utils/auth'
let wsUrl = `${process.env.VUE_APP_ORIGIN_API}messageService/websocket/message`

var websocket = null

var count = 0

// 获取websocket
export function getWebsocket() {
  return websocket
}

// 初始化websocket
export function initWebSocket(onmessage, onerror) {
  if (typeof WebSocket === 'undefined') {
    modal.msgError('websocket不支持!')
    return false
  }
  // 判断是否已经创建
  if (!websocket) {
    // ws请求完整地址
    const requstWsUrl = `${wsUrl}`
    // 创建websocket实例
    websocket = new WebSocket(requstWsUrl, getToken())
  }
  // 接收消息
  websocket.onmessage = function (e) {
    count = 0
    onmessage(e)
  }
  // 错误
  websocket.onerror = function (e) {
    modal.alert('websocket异常')
    console.log(e)
    onerror(e)
    websocket = null
  }
  // 关闭
  websocket.onclose = function (e) {
    count++
    console.log(e)
    console.log(`websocket连接关闭!正在重连${count}次...`)
    websocket = null
    var time = setTimeout(() => {
      // 断线重连
      initWebSocket(onmessage, onerror)
    }, 1000)
    if (count >= 10) {
      modal.alert(`websocket连接关闭!正在重连${count}次...`)
      clearTimeout(time)
      store.dispatch('user/logout')
      return false
    }
  }
}
